package com.tree.common.config.i18n.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.util.Properties;

/**
 * @ClassName com.demo.common.i18n.util
 * Description: <类功能描述>. <br>
 * <p>
 * <使用说明>
 * </p>
 * @Author tree
 * @Date 2019-05-24 23:32
 * @Version 1.0
 */
public class I18nResourceBundleMessageSource extends ReloadableResourceBundleMessageSource {
    private Logger logger = LoggerFactory.getLogger(I18nResourceBundleMessageSource.class);

    private static final String PROPERTIES_SUFFIX = ".properties";
    private ResourcePatternResolver resolver =new PathMatchingResourcePatternResolver();

    /**
     * filename --> spring.messages.basename
     * @param filename
     * @param propHolder
     * @return
     */
    @Override
    protected PropertiesHolder refreshProperties(String filename, PropertiesHolder propHolder) {
        Properties properties = newProperties();
        long lastModified= -1;
        try{
            //classpath*:messages/unify
            String name = "classpath*:"+filename.trim()+PROPERTIES_SUFFIX;
            Resource[] resources = resolver.getResources(name);
            for(Resource resource : resources){
                String sourcePath = resource.getURI().toString().replace(PROPERTIES_SUFFIX,"");
                PropertiesHolder holder = super.refreshProperties(sourcePath,propHolder);
                properties.putAll(holder.getProperties());
                if(lastModified < resource.lastModified()){
                    lastModified = resource.lastModified();
                }
            }
        }catch (Exception e){
            logger.error("",e);
        }

        return new PropertiesHolder(properties,lastModified);
    }
}
